<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="调出药库ID" prop="warehouseId" label-width="80">-->
<!--        <el-input-->
<!--          v-model="queryParams.warehouseId"-->
<!--          placeholder="请输入调出药库ID"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="调入药房ID" prop="pharmacyId" label-width="80">-->
<!--        <el-input-->
<!--          v-model="queryParams.pharmacyId"-->
<!--          placeholder="请输入调入药房ID"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="药品ID" prop="drugId">-->
<!--        <el-input-->
<!--          v-model="queryParams.drugId"-->
<!--          placeholder="请输入药品ID"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->

      <!-- 调出药库ID 搜索下拉框 -->
      <el-form-item label="调出药库ID" prop="warehouseId" label-width="80">
        <el-select
            v-model="queryParams.warehouseId"
        placeholder="请选择调出药库ID"
        clearable
        @change="handleQuery"
        >
        <el-option
            v-for="item in warehouseList"
        :key="item.warehouseId"
        :label="item.warehouseId"
        :value="item.warehouseId">
        </el-option>
        </el-select>
      </el-form-item>

      <!-- 调入药房ID 搜索下拉框 -->
      <el-form-item label="调入药房ID" prop="pharmacyId" label-width="80">
        <el-select
            v-model="queryParams.pharmacyId"
        placeholder="请选择调入药房ID"
        clearable
        @change="handleQuery"
        >
        <el-option
            v-for="item in pharmacyList"
        :key="item.pharmacyId"
        :label="item.pharmacyId"
        :value="item.pharmacyId">
        </el-option>
        </el-select>
      </el-form-item>

      <!-- 药品ID 搜索下拉框 -->
      <el-form-item label="药品ID" prop="drugId">
        <el-select
            v-model="queryParams.drugId"
        placeholder="请选择药品ID"
        clearable
        @change="handleQuery"
        >
        <el-option
            v-for="item in drugList"
        :key="item.drugId"
        :label="item.drugId"
        :value="item.drugId">
        </el-option>
        </el-select>
      </el-form-item>


      <el-form-item label="状态" prop="transferStatus">
        <el-select v-model="queryParams.transferStatus" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_oper_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['drug_transfer:drug_transfer:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['drug_transfer:drug_transfer:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['drug_transfer:drug_transfer:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['drug_transfer:drug_transfer:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="drug_transferList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="调单序号" align="center" prop="transferId" />
      <el-table-column label="调出药库ID" align="center" prop="warehouseId" />
      <el-table-column label="调入药房ID" align="center" prop="pharmacyId" />
      <el-table-column label="药品ID" align="center" prop="drugId" />
      <el-table-column label="调拨数量" align="center" prop="quantity" />
      <el-table-column label="状态" align="center" prop="transferStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_oper_type" :value="scope.row.transferStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['drug_transfer:drug_transfer:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['drug_transfer:drug_transfer:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改药品从药库调到药房对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">

        <el-form-item label="调出药库ID" prop="warehouseId">
          <el-select v-model="form.warehouseId" placeholder="请选择调出药库ID" clearable>
            <el-option
              v-for="item in warehouseList"
              :key="item.warehouseId"
              :label="item.warehouseName"
              :value="item.warehouseId">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 调入药房ID 下拉框 -->
        <el-form-item label="调入药房ID" prop="pharmacyId">
          <el-select v-model="form.pharmacyId" placeholder="请选择调入药房ID" clearable>
            <el-option
              v-for="item in pharmacyList"
              :key="item.pharmacyId"
              :label="item.pharmacyId"
            :value="item.pharmacyId">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 药品ID 下拉框 -->
        <el-form-item label="药品ID" prop="drugId">
          <el-select v-model="form.drugId" placeholder="请选择药品ID" clearable>
            <el-option
              v-for="item in drugList"
              :key="item.drugId"
              :label="item.drugName"
            :value="item.drugId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="调拨数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入调拨数量" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//此处需要查询到药库，药房，药品的id,整合时需要修改路径
import { listDrug_transfer, getDrug_transfer, delDrug_transfer, addDrug_transfer, updateDrug_transfer } from "@/api/drug_transfer/drug_transfer"
import { listManagement } from "@/api/BasicSettings/management" // 假设有这个API
import { listDrug_warehouse } from "@/api/warehouse/drug_warehouse"
import drugAndPharmacy from "@/api/pharmacy/mixins/drugAndPharmacy.js"


export default {
  name: "Drug_transfer",
  dicts: ['sys_oper_type'],
  mixins: [drugAndPharmacy],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 药品从药库调到药房表格数据
      drug_transferList: [],
      // 药品表格数据
      drugList: [],
      // 药房表格数据
      pharmacyList: [],
      //药库表格数据
      warehouseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseId: null,
        pharmacyId: null,
        drugId: null,
        transferStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        warehouseId: [
          { required: true, message: "调出药库ID不能为空", trigger: "blur" }
        ],
        pharmacyId: [
          { required: true, message: "调入药房ID不能为空", trigger: "blur" }
        ],
        drugId: [
          { required: true, message: "药品ID不能为空", trigger: "blur" }
        ],
        quantity: [
          { required: true, message: "调拨数量不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
    this.getDrugList()
    this.getWarehouseList()
    this.getPharmacyList()
  },
  methods: {
    /** 查询药品从药库调到药房列表 */
    getList() {
      this.loading = true
      listDrug_transfer(this.queryParams).then(response => {
        this.drug_transferList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 获取药品列表数据 */
    getDrugList(){
      listManagement(this.queryParams).then(response => {
        this.drugList = response.rows
        console.log("药品列表数据：", this.drugList)
      }).catch(error => {
        console.error("获取药品列表失败：", error)
      })
    /** 获取药房列表数据 - 修正版 */
    getPharmacyList() {
      return new Promise((resolve, reject) => {
        listPharmacy({
          pageSize: 1000,
          isValid: 1
        }).then(response => {
          console.log("药房API完整响应:", response);

          if (!response.rows || !Array.isArray(response.rows)) {
            console.error("药房API返回数据格式不正确");
            reject(new Error("药房API返回数据格式不正确"));
            return;
          }

          this.pharmacyList = response.rows;
          this.pharmacyMap = new Map();

          response.rows.forEach(item => {
            // 统一转换为字符串比较
            const id = String(item.pharmacyId);
            this.pharmacyMap.set(id, item.pharmacyName);
          });

          console.log("药房映射表内容:", Array.from(this.pharmacyMap.entries()));
          resolve();
        }).catch(error => {
          console.error("获取药房列表失败：", error);
          reject(error);
        });
      });
    },

    /** 获取药品列表数据 - 修正版 */
    getDrugList() {
      return new Promise((resolve, reject) => {
        this.loading = true;
        listDrug({
          pageSize: 1000,
          isValid: 1 // 只获取有效药品
        }).then(response => {
          console.log("药品API完整响应:", response);

          if (!response.rows || !Array.isArray(response.rows)) {
            console.error("药品API返回数据格式不正确");
            reject(new Error("药品API返回数据格式不正确"));
            return;
          }

          this.drugList = response.rows;
          this.drugMap = new Map();

          // 建立ID到名称的映射
          response.rows.forEach(item => {
            if (item.drugId && item.drugName) {
              const id = String(item.drugId);
              this.drugMap.set(id, item.drugName);
              console.log(`添加药品映射: ID=${id}, Name=${item.drugName}`);
            } else {
              console.warn("药品数据缺少必要字段:", item);
            }
          });

          console.log("药品映射表内容:", Array.from(this.drugMap.entries()));
          resolve();
        }).catch(error => {
          console.error("获取药品列表失败：", error);
          reject(error);
        }).finally(() => {
          this.loading = false;
        });
      });
    },

    /** 根据药房ID获取药房名称 - 修正版 */
    getPharmacyName(pharmacyId) {
      if (pharmacyId === null || pharmacyId === undefined) {
        return '无药房ID';
      }
      const id = String(pharmacyId);
      const name = this.pharmacyMap.get(id) || '未知药房';
      console.log(`获取药房名称: ID=${id}(${typeof id}), Name=${name}`);
      return name;
    },

    /** 获取药房列表数据 */
    getPharmacyList(){
      getPharmacyNameList(this.queryParams).then(response => {
        this.pharmacyList = response.rows
        console.log("药房列表数据：", this.pharmacyList)
      }).catch(error => {
        console.error("获取药房列表失败：", error)
      })
    /** 根据药品ID获取药品名称 - 修正版 */
    getDrugName(drugId) {
      if (drugId === null || drugId === undefined) {
        console.warn("药品ID为空");
        return '无药品ID';
      }

      // 统一转换为字符串比较
      const id = String(drugId);

      if (!this.drugMap.size) {
        console.warn("药品映射表为空");
        return '映射表未初始化';
      }

      const name = this.drugMap.get(id) || '未知药品';

      console.log(`获取药品名称详情:
      输入ID: ${drugId} (类型: ${typeof drugId})
      转换后ID: ${id} (类型: ${typeof id})
      获取结果: ${name}
      映射表大小: ${this.drugMap.size}
      是否存在该ID: ${this.drugMap.has(id)}`);

      return name;
    },

    /** 获取药库表格数据 */
    getWarehouseList(){
      listDrug_warehouse(this.queryParams).then(response => {
        this.warehouseList = response.rows
        console.log("药库列表数据：", this.warehouseList)

        // 建立ID到名称的映射
        response.rows.forEach(item => {
          this.warehouseMap.set(item.warehouseId, item.warehouseName)
        })
      }).catch(error => {
        console.error("获取药库列表失败：", error)
      })
    },

    /** 根据药库ID获取药库名称 */
    getWarehouseName(warehouseId) {
      return this.warehouseMap.get(warehouseId) || '未知药库'
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        transferId: null,
        warehouseId: null,
        pharmacyId: null,
        drugId: null,
        quantity: null,
        transferStatus: null,
        applyTime: null,
        confirmTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.transferId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加药品从药库调到药房"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const transferId = row.transferId || this.ids
      getDrug_transfer(transferId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改药品从药库调到药房"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.transferId != null) {
            updateDrug_transfer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addDrug_transfer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const transferIds = row.transferId || this.ids
      this.$modal.confirm('是否确认删除药品从药库调到药房编号为"' + transferIds + '"的数据项？').then(function() {
        return delDrug_transfer(transferIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('drug_transfer/drug_transfer/export', {
        ...this.queryParams
      }, `drug_transfer_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
